package studay.prototype;

import java.io.*;
import java.util.ArrayList;

/**
 * @program: 设计模式
 * @description: 建造者-原型设计模式
 * @author: Tom
 * @create: 2022-01-06 14:04
 **/
public class Person implements Cloneable, Serializable {

    private String name;

    private String age;

    private ArrayList list = new ArrayList();

    public Person(){
        System.out.println("构造函数使用");
    }

    public ArrayList getList() {
        return list;
    }

    public void setList(ArrayList list) {
        this.list = list;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    @Override
    public Person clone() throws CloneNotSupportedException {
        return (Person) super.clone();
    }

    /**
     * 深拷贝方法
     * 因为序列化之后内存地址会变更，就不会指向同一个地址
     * @return
     */
    public Person deepClone(){
        try {
            //输出序列化
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);

            // 输入 反序列化
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            Person copyObj = (Person) ois.readObject();
            return copyObj;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
